package com.jeespring.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.jeespring.common.constant.SystemConstant;
import com.jeespring.common.dto.TreeNode;
import com.jeespring.system.service.MenuService;
import com.jeespring.system.dao.MenuDao;
import com.jeespring.system.entity.Menu;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: MenuServiceImpl
 * @Description:
 * @Author 张朝阳
 * @Date 2019/12/21 13:04
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Menu> selectList(Menu menu,int pageNum,int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        menuDao.select(menu);
        return null;
    }

    @Override
    public List<Menu> selectAll() {
        return null;
    }

    @Override
    public List<Menu> select(Menu menu) {
        List<Menu> menuList = menuDao.select(menu);
        return menuList;
    }

    @Override
    public List<TreeNode> getMenuList(){
        Map<Long, List<TreeNode>> menuTree = new HashMap<>();
        //获取treeNodeList
        List<TreeNode> treeNodeList = menuDao.getMenuList();
        for (TreeNode treeNode : treeNodeList) {
            Long parentId = treeNode.getParentId();
            List<TreeNode> subTree = menuTree.get(parentId);
            if (subTree == null) {
                subTree = new ArrayList<>();
                menuTree.put(parentId, subTree);
            }
            subTree.add(treeNode);
        }
        List<TreeNode> menuList = menuTree.get(SystemConstant.ROOT_NODE);
        if(menuList == null){
            return null;
        }
        for (TreeNode node : menuList) {
            if (!SystemConstant.NodeType.LEAF.getCode().equals(node.getLeafNode()) ){
                getMenu(node , menuTree , node.getId());
            }
        }
        return menuList;
    }

    private void getMenu(TreeNode treeNode ,Map<Long ,List<TreeNode>> menuTree,Long parentId) {
        List<TreeNode> subTree = menuTree.get(parentId);
        if(subTree == null){
            return;
        }
        treeNode.setTreeNodeList(subTree);
        for (TreeNode node : subTree) {
            if (!SystemConstant.NodeType.LEAF.getCode().equals(node.getLeafNode())){
                getMenu(node , menuTree , node.getId());
            }
        }

    }
}
